package com.ycu.jk16.mall.util.common;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet返回JSONP格式数据
 */
public class JsonpServlet extends HttpServlet {
	private static final long serialVersionUID = -8343408864035108293L;

	/**
	 * 请求会发送callback參数作为回调函数，假设没有发送callback參数则使用默认回调函数
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// client发送的回调函数
		String callback = request.getParameter("callback");

		Map<String, Object> data = new HashMap<String, Object>();

		data.put("date", new Date());
		data.put("email", "sinclairni@163.com");
		data.put("age", 20);
		data.put("name", "nzl");
		data.put("array", new int[] { 1, 2, 3, 4 });

		if (callback == null || callback.length() == 0) {
			// 假设client没有发送回调函数。则使用默认的回调函数
			ResponseJsonUtils.jsonp(response, data);
		} else {
			// 使用client的回调函数
			ResponseJsonUtils.jsonp(response, callback, data);
		}
	}
}
